import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('输入框、表单'),
        ),
        body: LoginLayout(),
        // 使用表单组件简化LoginLayout
        // FormLayout(),
      ),
    );
  }
}

// 不使用表单的登录布局，无法对用户输入的字段做较好的判断（如用户不输入内容直接登录）
class LoginLayout extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        UsernameTextField(),
        PasswordTextField(),
        RaisedButton(
            child: Text('登录'),
            onPressed: () {
              // 清空输入框内容
              usernameController.text = "";
              debugPrint(
                  'username=${usernameController.text},password=${passwordController.text}');
            })
      ],
    );
  }
}

// 获取文本内容
TextEditingController usernameController = TextEditingController();
TextEditingController passwordController = TextEditingController();

// 改变键盘右下角图标以及动作
FocusNode passwordNode = FocusNode();

class UsernameTextField extends StatefulWidget {
  @override
  _UsernameTextFieldState createState() => _UsernameTextFieldState();
}

class _UsernameTextFieldState extends State<UsernameTextField> {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Theme(
        // 更改选中颜色
        data: ThemeData(primaryColor: Colors.amber),
        child: TextField(
          // 进入页面直接弹出键盘
          autofocus: true,
          // 一次性获取文本内容
          controller: usernameController,
          onChanged: (content) {
            debugPrint('username change:$content'); // 监听输入框文本变化
          },
          // 输入类型
          keyboardType: TextInputType.emailAddress,
          // 改变键盘右下角按钮图标样式
          textInputAction: TextInputAction.next,
          // 编辑完成，点击右下角按钮跳转到密码输入框passwordNode
          onEditingComplete: () =>
              FocusScope.of(context).requestFocus(passwordNode),
          decoration: InputDecoration(
              labelText: '用户名',
              hintText: '请输入用户名',
              // 矩形边框
              border: OutlineInputBorder(),
              icon: Icon(Icons.pets),
              // 设置填充颜色
              filled: true,
              fillColor: Colors.grey[350],
              prefixIcon: Icon(Icons.person)),
        ),
      ),
    );
  }
}

class PasswordTextField extends StatefulWidget {
  @override
  _PasswordTextFieldState createState() => _PasswordTextFieldState();
}

class _PasswordTextFieldState extends State<PasswordTextField> {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: TextField(
        controller: passwordController,
        maxLength: 6,
        // true强制仅仅输入6位，false当到达6位后显示红色
        maxLengthEnforced: false,
        // 隐藏文本，密码样式
        obscureText: true,
        textInputAction: TextInputAction.done,
        focusNode: passwordNode,
        // 点击提交
        onSubmitted: (content) {
          debugPrint(
              'username=${usernameController.text},password=${passwordController.text}');
        },
        decoration: InputDecoration(
            // 去除边框
            border: InputBorder.none,
            labelText: '密码',
            hintText: '请输入密码',
            prefixIcon: Icon(Icons.lock)),
      ),
    );
  }
}

// 使用表单组件，优雅的实现一次性校验、重置输入框
class FormLayout extends StatefulWidget {
  @override
  _FormLayoutState createState() => _FormLayoutState();
}

class _FormLayoutState extends State<FormLayout> {
  // 表单全局key，可以绑定一个表单，并获取表单状态
  GlobalKey<FormState> formGlobalKey = GlobalKey<FormState>();
  String _username;

  void save() {
    var form = formGlobalKey.currentState;
    // 验证表单,验证逻辑在每个输入框中
    if (form.validate()) {
      // 保存表单值，具体逻辑在每个表单中
      form.save();
      debugPrint(_username);
    } else {
      form.reset(); // 验证失败，清空表单
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Form(
            key: formGlobalKey,
            child: TextFormField(
              decoration: InputDecoration(labelText: '姓名', hintText: '请输入姓名'),
              // 表单验证
              validator: (content) {
                if (content.length < 4) {
                  return '至少4位';
                }
                return '';
              },
              onSaved: (content) {
                _username = content;
              },
            )),
        RaisedButton(
          child: Text('登录'),
          onPressed: save,
        )
      ],
    );
  }
}
